package com.dzu.gulimall.gulimall.sso.client.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhaoDong
 * @date 2022/6/29 17:47
 * @description gulimall
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    /**
     * 无需登录就可访问
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }


    /**
     * 感知这次是在ssoserver登陆成功后跳转过来的
     *
     * @param model
     * @param session
     * @param token 只要去sso server登陆成功就会跳回来 并带上token
     * @return
     */
    @GetMapping("/boss")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token",required = false) String token) {

        if (!StringUtils.isEmpty(token)) {
            //  去sso server中获取当前token中真正对应的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8880/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser", body);
        }


        Object attribute = session.getAttribute("loginUser");
        // 没登陆，。跳转到登陆服务器进行登陆
        if (attribute == null) {
//            登陆页面

            // 跳转过去后，使用url上的查询参数标识我们自己是哪个页面
            return "redirect:" + ssoServerUrl + "?redirect_url=http://client2.com:8882/boss";
        } else {
            List<String> list = new ArrayList<>();
            list.add("张三boss");
            list.add("里斯boss");
            model.addAttribute("emps", list);
            return "list";
        }
    }
}
